<template>
  <PageContainer>
    <a-layout>
      <a-layout-content>
        <a-card title="用户管理" style="margin-bottom: 20px">
          <a-form layout="inline" :model="searchFormState" ref="searchForm" @finish="search">
            <a-form-item label="用户名">
              <a-input v-model:value="searchFormState.username" placeholder="请输入用户名" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="searchFormState.status" placeholder="请选择状态">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="1">启用</a-select-option>
                <a-select-option value="2">离职</a-select-option>
                <a-select-option value="0">禁用</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="showAddModal">新增</a-button>
            </a-form-item>
          </a-form>
        </a-card>
        <a-table
          :data-source="tableData"
          :pagination="pagination"
          :loading="loading"
          :columns="columns"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="showEditModal(record.id)">修改</a-button>
              <a-button type="link" @click="showPasswordModal(record.id)">修改密码</a-button>
            </template>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
    <a-modal
      :title="!isEditing ? '新增用户' : '修改用户'"
      :visible="isModalVisible"
      @ok="handleOk"
      @cancel="handleCancel"
      transitionName="slide-fade"
      width="800px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" layout="vertical">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="用户名" name="username">
              <a-input v-model:value="formState.username" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="姓名" name="realName">
              <a-input v-model:value="formState.realName" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工号" name="employeeNumber">
              <a-input v-model:value="formState.employeeNumber" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8" v-if="!isEditing">
            <a-form-item label="密码" name="password">
              <a-input-password v-model:value="formState.password" />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="!isEditing">
            <a-form-item label="确认密码" name="doublePassword">
              <a-input-password v-model:value="formState.doublePassword" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="证件类型" name="documentType">
              <a-select v-model:value="formState.documentType">
                <a-select-option value="0">未知</a-select-option>
                <a-select-option value="1">身份证</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="证件号码" name="documentNumber">
              <a-input v-model:value="formState.documentNumber" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="手机号" name="mobile">
              <a-input v-model:value="formState.mobile" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="formState.email" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="用户状态" name="status">
              <a-select v-model:value="formState.status">
                <a-select-option value="1">启用</a-select-option>
                <a-select-option value="0">禁用</a-select-option>
                <a-select-option value="2">离职</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系地址" name="contactAddress">
              <a-input v-model:value="formState.contactAddress" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="备注">
              <a-textarea v-model:value="formState.remark" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <PasswordEditModal ref="passwordEditModalRef" />
  </PageContainer>
</template>

<script lang="ts" setup>
import { PageContainer as PageContainer } from '@ant-design-vue/pro-layout';
import { reactive } from 'vue';
import usePage from '@/composables/crud/usePage';
import useAddEditModal from '@/composables/crud/useAddEditModal';
import usePassword from '@/views/user/composables/usePassword';
import PasswordEditModal from '@/views/user/components/PasswordEditModal.vue';
import usePasswordData from '@/views/user/composables/usePasswordData';
import md5 from 'js-md5';
import { message } from 'ant-design-vue';
import { add, update } from '@/services';

const searchFormState = reactive({
  username: '',
  realName: '',
});

const { tableData, pagination, search, loading, searchForm } = usePage(
  'auth/rbacUser/validityPeriod',
  searchFormState,
);

const columns = [
  {
    title: '工号',
    dataIndex: 'employeeNumber',
    key: 'employeeNumber',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '姓名',
    dataIndex: 'realName',
    key: 'realName',
  },
  {
    title: '证件类型',
    dataIndex: 'documentType',
    key: 'documentType',
    customRender: ({ text }) => {
      switch (text) {
        case '0':
          return '未知';
        case '1':
          return '身份证';
        default:
          return '未知';
      }
    },
  },
  {
    title: '证件号码',
    dataIndex: 'documentNumber',
    key: 'documentNumber',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ text }) => {
      switch (text) {
        case '1':
          return '启用';
        case '0':
          return '禁用';
        case '2':
          return '离职';
        default:
          return '未知';
      }
    },
  },
  {
    title: '电子邮件',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    key: 'mobile',
  },
  { title: '操作', key: 'action' },
];

const formState = reactive({
  username: '',
  realName: '',
  employeeNumber: '',
  documentType: '',
  documentNumber: '',
  mobile: '',
  email: '',
  status: '',
  contactAddress: '',
  remark: '',
  password: '',
  doublePassword: '',
  originalPassword: '',
});

const { isModalVisible, isEditing, formRef, showAddModal, showEditModal, handleCancel } =
  useAddEditModal('auth/rbacUser', formState, search);

const handleOk = async () => {
  if (isEditing.value) {
    formState.password = '';
    formState.doublePassword = '';
    formState.originalPassword = '';
  }

  try {
    await formRef.value.validate();
  } catch (error) {
    message.error('表单验证失败，请检查输入');
    return;
  }

  let res;
  if (isEditing.value) {
    res = await update(`/api/auth/rbacUser`, formState);
  } else {
    let { password, doublePassword, originalPassword, ...rest } = formState;
    password = md5(password);
    doublePassword = md5(doublePassword);
    originalPassword = md5(originalPassword);
    res = await add(`/api/auth/rbacUser`, { password, doublePassword, originalPassword, ...rest });
  }

  const { success, data } = res;

  if (success) {
    message.info(`操作成功`);
    isModalVisible.value = false;
    if (search) {
      await search();
    }
    if (!isEditing.value) {
      await add(`/api/auth/rbacUserRole`, { userId: data.id, roleId: 1 });
    }
    return;
  }
  message.error(`保存失败`);
};

const { isPasswordModalVisible } = usePasswordData();
const validateDoublePassword2 = (rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请确认密码');
  }

  if (isPasswordModalVisible.value) {
    if (value !== passwordFormState.password) {
      return Promise.reject('两次输入的密码不一致');
    } else {
      return Promise.resolve();
    }
  }

  if (isModalVisible.value) {
    if (value !== formState.password) {
      return Promise.reject('两次输入的密码不一致');
    } else {
      return Promise.resolve();
    }
  }
};
const validateDocumentNumber = (rule: any, value: string) => {
  const documentType = formState.documentType;
  if (documentType === '1') {
    // 1 表示身份证
    const idCardPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardPattern.test(value)) {
      return Promise.reject('请输入有效的身份证号码');
    }
  }
  return Promise.resolve();
};
const { validatePassword } = usePasswordData();

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  doublePassword: [{ validator: validateDoublePassword2, trigger: 'blur' }],
  employeeNumber: [{ required: true, message: '请输入员工编号', trigger: 'blur' }],
  documentType: [{ message: '请选择证件类型', trigger: 'change' }],
  documentNumber: [{ validator: validateDocumentNumber, trigger: 'blur' }],
  mobile: [
    { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
  ],
  email: [{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }],
  status: [{ required: true, message: '请选择用户状态', trigger: 'change' }],
  contactAddress: [{ message: '请输入联系地址', trigger: 'blur' }],
  remark: [{ max: 200, message: '备注不能超过200个字符', trigger: 'blur' }],
};

const { showPasswordModal, passwordEditModalRef } = usePassword();
</script>

<style lang="less" scoped></style>
